package com.chlitina.store.modules.cash.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.chlitina.store.common.config.Global;
import com.chlitina.store.common.mapper.JsonMapper;
import com.chlitina.store.common.persistence.Page;
import com.chlitina.store.common.utils.DateUtils;
import com.chlitina.store.common.utils.StoreCareUtils;
import com.chlitina.store.common.utils.StoreProductUtils;
import com.chlitina.store.common.web.BaseController;
import com.chlitina.store.modules.base.entity.Customer;
import com.chlitina.store.modules.base.entity.StoreCare;
import com.chlitina.store.modules.base.entity.StoreProduct;
import com.chlitina.store.modules.base.service.CustomerService;
import com.chlitina.store.modules.base.service.StoreCareService;
import com.chlitina.store.modules.base.service.StoreProductService;
import com.chlitina.store.modules.cash.entity.StoreConsume;
import com.chlitina.store.modules.cash.model.ConsumeHistory;
import com.chlitina.store.modules.cash.model.ShoppingCart;
import com.chlitina.store.modules.cash.model.StoreCareCart;
import com.chlitina.store.modules.cash.model.StoreProductCart;
import com.chlitina.store.modules.cash.service.NomemberService;
import com.chlitina.store.modules.cash.service.StoreConsumeService;
import com.chlitina.store.modules.cash.utils.StoreCashUtils;
import com.chlitina.store.modules.employee.dao.EmployeeDao;
import com.chlitina.store.modules.employee.entity.Employee;
import com.chlitina.store.modules.sys.entity.Store;
import com.chlitina.store.modules.sys.utils.StoreUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

/**
 * Crash Controller
 * 
 * @author Songsong.xu
 * @version 2013-3-23
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH + "/cash/consume")
public class NonMemberController extends BaseController {
	@Autowired
	private StoreConsumeService storeConsumeService;
	@Autowired
	private NomemberService nomemberService;

	@Autowired
	private EmployeeDao employeeDao;
	@Autowired
	private StoreCareService storeCareService;
	@Autowired
	private StoreProductService storeProductService;
	@Autowired
	private CustomerService customerService;

	private String KEY_SHOPPING_CART = "shoppingCart";

	@RequestMapping(value = { "cashNonmemberForm" })
	public String addNonmember(Customer customer, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		return "modules/cash/cashNonmemberForm";
	}

	String URI_BUY_STORE_PRODUCT_PAGE = "modules/cash/buyStoreProductPage";
	String URI_DO_STORE_CARE_PAGE = "modules/cash/doStoreCarePage";
	String URI_CONSUME_DETAIL_PAGE = "modules/cash/consumeDetailPage";

	String getDirectURL(String uri, Map<String, String> params) {
		return Global.getDirectURL("cash/consume/" + uri, params);
	}

	String getDirectURL(String uri) {
		return Global.getDirectURL("cash/consume/" + uri, null);
	}

	@RequestMapping(value = { "cashStoreProducts" })
	public String storeProducts(ShoppingCart shoppingCart,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		model.addAttribute(KEY_SHOPPING_CART, shoppingCart);
		registerCarts(model);
		return "modules/cash/cashStoreProducts";
	}

	@ResponseBody
	@RequestMapping(value = { "clientLoadingProduct" })
	public String clientLoadingProduct(HttpServletRequest request,
			HttpServletResponse response, String type) {
		List<StoreProduct> storeProducts = null;
		if (Types.system.equalsIgnoreCase(type)) {
			storeProducts = nomemberService.findSystemProducts();
		} else if (Types.storeself.equalsIgnoreCase(type)) {
			storeProducts = nomemberService.findStoreSelfProducts();
		} else {

		}
		List<Map<String, Object>> set = Lists.newArrayList();
		Map<String, Object> map = null;
		ShoppingCart shoppingCart = getShoppingCart(request);
		if (shoppingCart != null) {
			map = Maps.newHashMap();
			map.put("result", true);
			List<StoreProductCart> products = shoppingCart.getProducts();
			List<Map<String, Object>> addedSet = Lists.newArrayList();
			for (StoreProductCart storeProductCart : products) {
				map = Maps.newHashMap();
				map.put("id", storeProductCart.getStoreProduct().getId());
				addedSet.add(map);
			}
			System.err.println(JsonMapper.getInstance().toJson(addedSet));
			map.put("addedProducts", JsonMapper.getInstance().toJson(addedSet));
			set.add(map);

			if (storeProducts != null) {
				for (StoreProduct storeProduct : storeProducts) {
					if (storeProduct.getAmount() < 1) {
						continue;
					}
					map = Maps.newHashMap();
					map.put("id", storeProduct.getId());
					map.put("amount", storeProduct.getAmount());
					map.put("category",
							StoreProductUtils.getCategory(storeProduct));
					map.put("name", StoreProductUtils.getName(storeProduct));
					map.put("retailPrice",
							StoreProductUtils.getRetailPrice(storeProduct));
					map.put("spec", StoreProductUtils.getSpec(storeProduct));
					set.add(map);
				}
			}
		} else {
			map = Maps.newHashMap();
			map.put("result", false);
			map.put("message", "状态丢失");
			set.add(map);
		}

		System.err.println(JsonMapper.getInstance().toJson(set));
		return JsonMapper.getInstance().toJson(set);
	}

	@ResponseBody
	@RequestMapping(value = { "clientDeleteCare" })
	public String clientDeleteCare(HttpServletRequest request,
			HttpServletResponse response, String cartID) {
		boolean result = true;
		String message = "";
		StoreCareCart cart = null;
		ShoppingCart shoppingCart = (ShoppingCart) request.getSession()
				.getAttribute(KEY_SHOPPING_CART);
		if (shoppingCart == null) {
			result = false;
			message = "状态丢失";
		} else {
			long id = Long.parseLong(cartID);
			List<StoreCareCart> cares = shoppingCart.getCares();
			for (StoreCareCart storeCareCart : cares) {
				if (storeCareCart.getId() == id) {
					cart = storeCareCart;
					break;
				}
			}
			if (cart == null) {
				result = false;
				message = "错误的护理编号，未找到匹配项目";
			} else {
				cares.remove(cart);
				result = true;
				message = "删除成功";
			}
		}

		Set<Map<String, Object>> set = Sets.newHashSet();
		Map<String, Object> map = Maps.newHashMap();
		map.put("id", cart != null ? cart.getStoreCare().getId() : "");
		map.put("result", result);
		map.put("message", message);
		set.add(map);
		System.err.println(JsonMapper.getInstance().toJson(set));
		return JsonMapper.getInstance().toJson(set);
	}

	@ResponseBody
	@RequestMapping(value = { "clientAddCare" })
	public String clientAddCare(HttpServletRequest request,
			HttpServletResponse response, String careID, String employeeID,
			String amount, String type) {
		boolean result = true;
		String message = "";
		long cartID = 0;
		ShoppingCart shoppingCart = (ShoppingCart) request.getSession()
				.getAttribute(KEY_SHOPPING_CART);
		if (shoppingCart == null) {
			result = false;
			message = "状态丢失";
		} else {
			try {
				long id = Long.parseLong(careID);
				StoreCare storeCare = storeCareService.get(id);
				if (storeCare == null) {
					result = false;
					message = "错误的护理编号，未找到匹配项目";
				} else {
					List<StoreCareCart> cares = shoppingCart.getCares();
					Employee employee = employeeDao.findOne(Long
							.parseLong(employeeID));
					if (employee == null) {
						result = false;
						message = "错误的员工编号，未找到匹配员工";
					} else {
						StoreCareCart cart = new StoreCareCart();
						cart.setEmployee(employee);
						cart.setCount(Integer.parseInt(amount));
						cart.setStoreCare(storeCare);
						cart.setSinglePrice(StoreCareUtils.getSinglePrice(storeCare));
						cares.add(cart);
						shoppingCart.generateCareCartId(cart);
						cartID = cart.getId();
						result = true;
						message = "添加成功";
					}
				}
			} catch (NumberFormatException e) {
				result = false;
				message = "错误的产品编号，未找到匹配产品";
			}
		}

		Set<Map<String, Object>> set = Sets.newHashSet();
		Map<String, Object> map = Maps.newHashMap();
		map.put("cartID", cartID);
		map.put("id", cartID);
		map.put("result", result);
		map.put("message", message);
		set.add(map);
		System.err.println(JsonMapper.getInstance().toJson(set));
		return JsonMapper.getInstance().toJson(set);
	}

	@ResponseBody
	@RequestMapping(value = { "clientLoadingCare" })
	public String clientLoadingCare(HttpServletRequest request,
			HttpServletResponse response, String type) {
		List<StoreCare> storeCares = null;
		if (Types.system.equalsIgnoreCase(type)) {
			storeCares = nomemberService.findSystemCares();
		} else if (Types.storeself.equalsIgnoreCase(type)) {
			storeCares = nomemberService.findStoreSelfCares();
		} else {

		}
		List<Map<String, Object>> set = Lists.newArrayList();
		Map<String, Object> map = null;
		ShoppingCart shoppingCart = getShoppingCart(request);
		if (shoppingCart != null) {
			map = Maps.newHashMap();
			map.put("result", true);
			List<StoreCareCart> cares = null;
			if (Types.system.equals(type)) {
				cares = shoppingCart.getSystemCares();
			} else {
				cares = shoppingCart.getStoreCares();
			}
			List<Map<String, Object>> addedSet = Lists.newArrayList();
			for (StoreCareCart cart : cares) {
				map = Maps.newHashMap();
				map.put("id", cart.getStoreCare().getId());
				addedSet.add(map);
			}
			System.err.println(JsonMapper.getInstance().toJson(addedSet));
			map.put("addedCares", JsonMapper.getInstance().toJson(addedSet));
			set.add(map);

			if (storeCares != null) {
				for (StoreCare care : storeCares) {
					map = Maps.newHashMap();
					map.put("id", care.getId());
					map.put("name", StoreCareUtils.getName(care));
					map.put("retailPrice", StoreCareUtils.getSinglePrice(care));
					map.put("fullPrice", StoreCareUtils.getRetailPrice(care));
					map.put("decription", StoreCareUtils.getDescription(care));
					map.put("duration", StoreCareUtils.getDuration(care));
					map.put("typeString", StoreCareUtils.getTypeString(care));
					map.put("times", StoreCareUtils.getTimes(care));
					set.add(map);
				}
			}
		} else {
			map = Maps.newHashMap();
			map.put("result", false);
			map.put("message", "状态丢失");
			set.add(map);
		}

		System.err.println(JsonMapper.getInstance().toJson(set));
		return JsonMapper.getInstance().toJson(set);
	}

	@ResponseBody
	@RequestMapping(value = { "clientDeleteProduct" })
	public String clientDeleteProduct(HttpServletRequest request,
			HttpServletResponse response, String productID, String type) {
		boolean result = true;
		String message = "";
		if (Types.system.equals(type) || Types.storeself.equals(type)) {
			ShoppingCart shoppingCart = (ShoppingCart) request.getSession()
					.getAttribute(KEY_SHOPPING_CART);
			if (shoppingCart == null) {
				result = false;
				message = "状态丢失";
			} else {
				StoreProduct storeProduct = storeProductService.get(Long
						.parseLong(productID));
				if (storeProduct == null) {
					result = false;
					message = "错误的产品编号，未找到匹配产品";
				} else {
					shoppingCart.deleteProduct(storeProduct.getId().intValue());
					result = true;
					message = "删除成功";
				}
			}
		} else {
			result = false;
			message = "错误的产品类型";
		}

		Set<Map<String, Object>> set = Sets.newHashSet();
		Map<String, Object> map = Maps.newHashMap();
		map.put("id", productID);
		map.put("result", result);
		map.put("message", message);
		set.add(map);
		System.err.println(JsonMapper.getInstance().toJson(set));
		return JsonMapper.getInstance().toJson(set);
	}

	@ResponseBody
	@RequestMapping(value = { "clientAddProduct" })
	public String clientAddProduct(HttpServletRequest request,
			HttpServletResponse response, String productID, String employeeID,
			String amount, String editing) {
		boolean result = true;
		String message = "";
		ShoppingCart shoppingCart = (ShoppingCart) request.getSession()
				.getAttribute(KEY_SHOPPING_CART);
		if (shoppingCart == null) {
			result = false;
			message = "状态丢失";
		} else {
			try {
				StoreProductCart cart = null;
				boolean edit = "update".equals(editing);
				long id = Long.parseLong(productID);
				long required=Long.parseLong(amount);
				StoreProduct storeProduct = storeProductService.get(id);
				if (storeProduct == null) {
					result = false;
					message = "错误的产品编号，未找到匹配产品";
				} else {
					if(required>storeProduct.getAmount() ||storeProduct.getAmount()==0){
						result = false;
						message = "库存不足，剩余库存："+storeProduct.getAmount();
					}else{
						List<StoreProductCart> products = shoppingCart
								.getProducts();
						if (StoreCashUtils.exist(products, storeProduct.getId())
								&& !edit) {
							result = false;
							message = "不能重复添加产品";
						} else {
							Employee employee = employeeDao.findOne(Long
									.parseLong(employeeID));
							if (employee == null) {
								result = false;
								message = "错误的员工编号，未找到匹配员工";
							} else {
								if (edit) {
									cart = StoreCashUtils.find(products, id);
									cart.setCount(Integer.parseInt(amount));
									message = "更新成功";
									result = true;
								} else {
									cart = new StoreProductCart();
									cart.setEmployee(employee);
									cart.setStoreProduct(storeProduct);
									cart.setCount(Integer.parseInt(amount));
									products.add(cart);
									message = "添加成功";
									result = true;
								}
							}
						}
					}
					
					
				}
			} catch (NumberFormatException e) {
				result = false;
				message = "错误的产品编号，未找到匹配产品";
			}
		}

		Set<Map<String, Object>> set = Sets.newHashSet();
		Map<String, Object> map = Maps.newHashMap();
		map.put("id", productID);
		map.put("result", result);
		map.put("message", message);
		map.put("amount", amount);
		map.put("editing", editing);
		set.add(map);
		System.err.println(JsonMapper.getInstance().toJson(set));
		return JsonMapper.getInstance().toJson(set);
	}

	@ResponseBody
	@RequestMapping(value = { "canCommit" })
	public String canCommit(HttpServletRequest request,
			HttpServletResponse response) {
		ShoppingCart shoppingCart = getShoppingCart(request);
		boolean result = false;
		if (shoppingCart == null) {
			result = false;
		} else {
			result = !shoppingCart.getProducts().isEmpty()
					|| !shoppingCart.getCares().isEmpty();
		}
		return JsonMapper.getInstance().toJson(result);
	}

	@ResponseBody
	@RequestMapping(value = { "storeProduct/canBuyProduct",
			"product/canBuyProduct", "canBuyProduct" })
	public String canBuyProduct(String productID, String count) {
		String[] resut = { "false", "0" };
		try {
			long required = Long.parseLong(count);
			long id = Long.parseLong(productID);
			long amount = StoreCashUtils.currentProductAmount(
					StoreUtils.getMember(), id);
			if (amount >= required) {
				resut[0] = "" + true;
				resut[1] = amount + "";
				return JsonMapper.getInstance().toJson(resut);
			} else {
				resut[1] = amount + "";
				return JsonMapper.getInstance().toJson(resut);
			}
		} catch (Exception e) {
			return JsonMapper.getInstance().toJson(resut);
		}
	}

	@ResponseBody
	@RequestMapping(value = { "isCustomerExist" })
	public String isCustomerExist(String name, String mobile) {
		List<Customer> list = customerService.isUnique(mobile);
		List<HashMap<Object, Object>> jsonArray = Lists.newArrayList();
		HashMap<Object, Object> jsonState = null, jsonOnject = null;
		jsonState = Maps.newHashMap();
		jsonState.put("amount", list.size());
		jsonState.put("mobile", mobile);
		jsonState.put("result", list.isEmpty());
		jsonArray.add(jsonState);
		for (Customer c : list) {
			if (name != null && name.equals(c.getName())) {
				continue;
			}
			jsonOnject = Maps.newHashMap();
			jsonOnject.put("id", c.getId());
			jsonOnject.put("name", c.getName());
			jsonOnject.put("nickname",
					c.getNickname() == null ? "" : c.getNickname());
			jsonOnject.put("storeName", c.getStore().getName());
			jsonOnject.put("storeAddress", c.getStore().getAddress());
			jsonOnject
					.put("mobile", c.getMobile() == null ? "" : c.getMobile());
			jsonArray.add(jsonOnject);
		}
		jsonState.put("result", (jsonArray.size() < 2)+"");
		return JsonMapper.getInstance().toJson(jsonArray);
	}

	/**
	 * Consume detail page
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = { "consumeDetailPage" })
	public String consumeDetailPage(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {
		String consumeID = request.getParameter("consumeID");
		if (consumeID == null) {
			addMessage(redirectAttributes, "状态丢失");
			return getDirectURL("nonmember");
		}
		try {
			long cID = Long.parseLong(consumeID);
			String jsonData = storeConsumeService
					.findNomemberConsumeDetail(cID);
			model.addAttribute("jsonData", jsonData);
		} catch (NumberFormatException e) {
			addMessage(redirectAttributes, "状态丢失");
			return getDirectURL("nonmember");
		}
		return URI_CONSUME_DETAIL_PAGE;
	}

	/**
	 * Do Store cares
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = { "doStoreCarePage" })
	public String doStoreCarePage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		ShoppingCart shoppingCart = getShoppingCart(request);
		if (shoppingCart == null) {
			model.addAttribute("message", "状态丢失");
			return listNonmembers(new ConsumeHistory(), request, response,
					model);
		}
		model.addAttribute(KEY_SHOPPING_CART, shoppingCart);
		registerCarts(model);
		return URI_DO_STORE_CARE_PAGE;
	}

	/**
	 * buy Store Product
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = { "buyStoreProductPage" })
	public String buyStoreProductPage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		ShoppingCart shoppingCart = getShoppingCart(request);
		if (shoppingCart == null) {
			model.addAttribute("message", "状态丢失");
			return listNonmembers(new ConsumeHistory(), request, response,
					model);
		}
		model.addAttribute(KEY_SHOPPING_CART, shoppingCart);
		registerCarts(model);
		return URI_BUY_STORE_PRODUCT_PAGE;
	}

	ShoppingCart getShoppingCart(HttpServletRequest request) {
		Object attribute = request.getSession().getAttribute(KEY_SHOPPING_CART);
		if (attribute instanceof ShoppingCart) {
			return (ShoppingCart) attribute;
		}
		return null;
	}

	@RequestMapping(value = { "unsaveCustomer" })
	public String unsaveCustomer(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		ShoppingCart shoppingCart = getShoppingCart(request);
		if (shoppingCart == null) {
			shoppingCart = new ShoppingCart();
			shoppingCart.setDatetime(DateUtils.getDate());
			request.getSession().setAttribute(KEY_SHOPPING_CART, shoppingCart);
			model.addAttribute(KEY_SHOPPING_CART, shoppingCart);
		} else {
			model.addAttribute(KEY_SHOPPING_CART, shoppingCart);
		}
		registerCarts(model);
		return URI_BUY_STORE_PRODUCT_PAGE;
	}

	/**
	 * 当用户点击“确认添加客户资料” 或者“暂不添加客户资料” 都由该方法控制处理，如果需要添加客户资料，则立即快速注册会员，否则直接跳转至消费界面
	 * 
	 * @param customer
	 *            客户：散客或者会员（由ID控制，当ID为null时，则为散客，否则为注册会员）
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = { "saveCustomer" })
	public String saveNonmember(Customer customer, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		if (customer.getName() != null) {
			Long id = null;
			// 注册会员
			if (customer.getName() == null
					|| "".equals(customer.getName().trim())
					|| customer.getMobile() == null
					|| "".equals(customer.getMobile().trim())) {
				model.addAttribute("message", "用户的名字，以及电话号码均不能为空，请重新输入");
				return addNonmember(customer, request, response, model);
			}
			List<Customer> list = customerService
					.isUnique(customer.getMobile());
			if (list.size() > 0) {
				if (!list.get(0).getName().equals(customer.getName())
						|| list.size() > 1) {
					model.addAttribute("message", "用户已经存在，不能重复添加");
					return addNonmember(customer, request, response, model);
				} else {
					id = list.get(0).getId();
				}
			} else {
				customer.setStore(StoreUtils.getStore());
				customerService.save(customer);
				id = customer.getId();
			}
			if (id == null) {
				model.addAttribute("message", "注册失败，请重新注册");
				return addNonmember(customer, request, response, model);
			} else {
				// goto Member Shopping
				return "redirect:" + Global.ADMIN_PATH
						+ "/cash/member/detail?id=" + id.longValue();
			}
		}
		return addNonmember(customer, request, response, model);
	}

	@RequestMapping(value = { "payNonmembers" })
	public String payNonmember(ShoppingCart paramCart, Customer customer,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		ShoppingCart shoppingCart = getShoppingCart(request);
		if (shoppingCart == null) {
			model.addAttribute("message", "状态丢失");
			return listNonmembers(new ConsumeHistory(), request, response,
					model);
		}
		// update Prices
		shoppingCart.updatePayElement();
		model.addAttribute(KEY_SHOPPING_CART, shoppingCart);
		registerCarts(model);
		model.addAttribute("history", new ConsumeHistory());
		return "modules/cash/cashNonmemberConsumePay";
	}

	@RequestMapping(value = { "nonmember/dropShopping" })
	public String dropShopping(ShoppingCart shoppingCart,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		request.getSession().removeAttribute(KEY_SHOPPING_CART);
		return getDirectURL("nonmember");
	}

	@RequestMapping(value = { "payNonmembers/commit" })
	public String payCommitNonmember(Customer customer,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		ShoppingCart shoppingCart = (ShoppingCart) request.getSession()
				.getAttribute(KEY_SHOPPING_CART);
		if (shoppingCart == null) {
			model.addAttribute("message", "状态丢失");
			return listNonmembers(new ConsumeHistory(), request, response,
					model);
		}
		StoreConsume consume = storeConsumeService
				.commitNonmember(shoppingCart);
		if (consume != null) {
			// clear session;
			request.getSession().removeAttribute(KEY_SHOPPING_CART);
			Map<String, String> params = Maps.newHashMap();
			params.put("consumeID", consume.getId().longValue() + "");
			return getDirectURL("consumeDetailPage", params);
		}
		// update Prices
		shoppingCart.updatePayElement();
		model.addAttribute(KEY_SHOPPING_CART, shoppingCart);
		registerCarts(model);
		return "modules/cash/cashNonmemberConsumeMain";
	}

	public void updateEmployee(HttpServletRequest request) {
		HttpSession session = request.getSession();
		Object attribute = session.getAttribute("employees");
		if (attribute == null) {
			session.setAttribute("employees",
					employeeDao.findListByStore(StoreUtils.getStore().getId(),Employee.STATUS_WORKING));
		} else if (attribute instanceof List<?>) {
			List<?> a = (List<?>) attribute;
			if (a.size() == 0) {
				session.setAttribute("employees", employeeDao
						.findListByStore(StoreUtils.getStore().getId(),Employee.STATUS_WORKING));
			}
		}
	}

	private void registerCarts(Model model) {
		model.addAttribute("storeCare", new StoreCareCart());
		model.addAttribute("systemCare", new StoreCareCart());
		model.addAttribute("storeProduct", new StoreProductCart());
		model.addAttribute("systemProduct", new StoreProductCart());
	}

	@RequestMapping(value = { "historyNonmembers" })
	public String historyNonmembers(ConsumeHistory history,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		storeConsumeService.findNomemberConsumes(history,new Page<StoreConsume>(request, response));
		model.addAttribute("history", history);
		return "modules/cash/cashNonmemberConsume";
	}

	@RequestMapping(value = { "nonmember" })
	public String listNonmembers(ConsumeHistory history,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Object attribute = request.getSession().getAttribute(KEY_SHOPPING_CART);
		storeConsumeService.findNomemberConsumes(history,new Page<StoreConsume>(request, response));
		model.addAttribute("history", history);
		updateEmployee(request);
		if (attribute != null) {
			model.addAttribute(KEY_SHOPPING_CART, attribute);
			registerCarts(model);
			return URI_BUY_STORE_PRODUCT_PAGE;
		}
		return "modules/cash/cashNonmemberConsume";
	}

	@RequestMapping(value = { "member/search" })
	public String search(Customer customer, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Store store = StoreUtils.getStore();
		String type = request.getParameter("searchType");
		String keyWord = request.getParameter("keyWord");
		if (store != null) {
			customer.setStore(store);
		}
		Page<Customer> page = customerService.find(new Page<Customer>(request,
				response), type, keyWord);
		model.addAttribute("page", page);
		model.addAttribute("customerName", customer.getName());
		if (page.getCount() == 0) {
			model.addAttribute("message", "无结果");
		}
		return "modules/cash/cashMemberConsume";
	}
}
